package com.apache.database.constant;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;

import com.apache.cache.service.CacheManager;
import com.apache.cache.service.impl.LoadCacheFactory;
import com.apache.tools.ConfigUtil;

/**
 * description: 系统工具类
 */
public class SystemTools {

	protected Logger log = Logger.getLogger(getClass());

	private static SystemTools instance;

	private Map<String, CacheManager> cachePool = new HashMap<String, CacheManager>();//缓存池

	private long lastUpateTime = 0l;//最后修改时间

	private Map<String, String> constant = new HashMap<String, String>();//存放系统配置参数

	private String filePath = "";

	private SystemTools() {
		filePath = Validator.getClassLoaderPath() + "config/";
	}

	/**
	 * description: 启用单例模式
	 *
	 * @return
	 */
	public synchronized static SystemTools getInstance() {
		if (null == instance) {
			instance = new SystemTools();
		}
		return instance;
	}

	/**
	 * description: 获取缓存对象
	 *
	 * @param spaceName 缓存空间名
	 * @return
	 */
	public synchronized CacheManager getCache(String spaceName) {
		spaceName = Validator.getDefaultStr(spaceName,
				LoadCacheFactory.getInstance().getProperty("cache_default_name"));
		if (Validator.isEmpty(cachePool.get(spaceName))) {
			cachePool.put(spaceName, LoadCacheFactory.getInstance().getCacheManager(spaceName));
		}
		return cachePool.get(spaceName);
	}

	/**
	 * description:  是否为redis缓存
	 *
	 * @return
	 */
	public boolean isRedisCache() {
		String type = LoadCacheFactory.getInstance().getProperty("cache_type");
		if ("redis".equalsIgnoreCase(type)) {
			return true;
		}
		return false;
	}

	/**
	 * description: 加载配置文件
	 */
	private String initConfig(String key) {
		synchronized (this) {
			String fileName = ConfigUtil.UNITY_CINFIG;
			boolean mark = constant.isEmpty();
			Properties prop = ConfigUtil.getInstance().getConfigForCache("", fileName, mark);
			if (null == prop || prop.isEmpty()) {//不启用缓存
				if (filePath.indexOf(".jar") != -1) {
					if (constant.isEmpty()) {
						prop = getProperties(filePath, fileName);
					}
				} else {
					File oldfile = new File(filePath + fileName);
					long lastModletime = oldfile.lastModified();
					if (lastUpateTime < lastModletime) {//有更新从新加载
						lastUpateTime = lastModletime;
						prop = getProperties(filePath, fileName);
					}
				}
			}
			if (!Validator.isEmpty(prop) && !prop.isEmpty()) {//有更新从新加载
				log.info("开始加载配置文件：" + fileName);
				Map<String, String> map = new HashMap<String, String>((Map) prop);
				Set propertySet = map.entrySet();
				for (Object o : propertySet) {
					Map.Entry entry = (Map.Entry) o;
					constant.put(entry.getKey().toString(), entry.getValue().toString());
					log.info(entry.getKey().toString() + "=" + entry.getValue().toString());
				}
			}
		}
		if (Validator.isNull(key))
			return "";
		else
			return Validator.getDefaultStr(constant.get(key), "");
	}

	private Properties getProperties(String filePath, String fileName) {
		Properties prop = null;
		FileInputStream fileInput = null;
		InputStream stream = null;
		try {
			if (filePath.indexOf(".jar") != -1) {
				stream = SystemTools.class.getClassLoader().getResourceAsStream("config/" + fileName);
				prop = new Properties();
				prop.load(stream);
			} else {
				File file = new File(filePath + fileName);
				if (file.exists()) {// 判断文件夹是否存在
					prop = new Properties();
					fileInput = new FileInputStream(filePath + fileName);
					prop.load(fileInput);
				}
			}
		} catch (Exception e) {
			System.out.println("文件读取失败! key=" + e.getMessage());
		} finally {
			IOUtils.closeQuietly(fileInput);
			IOUtils.closeQuietly(stream);
		}
		return prop;
	}

	/**
	 * description: 获取所有配置信息
	 *
	 * @return
	 */
	public Map<String, String> getMap() {
		initConfig("");
		return constant;
	}

	/**
	 * description: 根据指定的KEY获取相应配置信息
	 *
	 * @param key 指定的KEY
	 * @return
	 */
	public String getValue(String key) {
		return initConfig(key);
	}

	public String getValue(String key, String charset) {
		try {
			charset = Validator.getDefaultStr(charset, "UTF-8");
			String result = new String(initConfig(key).getBytes("iso8859-1"), charset);
			return result;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return "";
	}
}
